<?php
/**
 * User
 *
 * PHP version 5
 *
 * @category Controller
 * @version  1.0
 * @author   Duonght <hduongdmit@gmail.com>
 */
App::uses('AppController', 'Controller');
class LegelDocsController extends AppController {

	const CAT_TYPE = "'legel_docs'";
	/**
	* Components
	* @var array
	*/
	public $components = array(
			'Paginator',
			'Upload',
			'Common',
	);
	public $helper = array('Utilities');
	public $uses = array('LegelDocs', 'Category');
	private $categorymulti = array();
	private $stt = -1;

	public function beforeFilter(){
		parent::beforeFilter();
		$category_type = Configure::read('category_type');
		$this->set('category_type', $category_type);
	}

	public function index(){
		//get category parent
		$listCategory = $this->Category->getListCategoryType(self::CAT_TYPE);
		$listCatId = '';
		$total = count($listCategory);
		foreach ($listCategory as $key => $category){
			$key++;
			foreach ($category as $value){
				if ($key != $total) {
					$sem = ',';
				} else {
					$sem = '';
				}

				$listCatId .= $value['id'] . $sem;
			}
		}

		//get all static page
		$conditions = array('del_flg' => 0, 'category_id IN ('.$listCatId.')');

		if ($this->request->is('post')) {
			$params = $this->request->data;
			$name = $params['LegelDocs']['name'];
			$conditions['or'] = array(
					'LegelDocs.name LIKE' => '%'. $name. '%',
					'LegelDocs.brief LIKE' => '%'. $name .'%',
					'LegelDocs.contents LIKE' => '%'. $name .'%',
			);

		}

		$paginate = array(
				'fields' => array(
						'id',
						'category_id',
						'name',
						'new_picture',
						'create_time',
						'last_update',
						'new_rewrite',
						'active',
						'new_hits',
						'del_flg',
						'Categories.cat_rewrite',
				),
				'joins'=>array(
					array(
						'table'=>'categories_multi',
						'type'=>'inner',
						'alias'=>'Categories',
						'conditions'=>array('LegelDocs.category_id = Categories.id')
					)
				),
				'limit' => ConstAdminComponent::PAGE_NUMBER_LIMIT,
				'conditions' => $conditions,
				'order' => array(
					'last_update' => 'DESC',
				),
		);

		$this->Paginator->settings = $paginate;
		$listNews = $this->Paginator->paginate('LegelDocs');

		//force view
		$this->set(array(
				'datas' => $listNews,
				'page_number_limit' => ConstAdminComponent::PAGE_NUMBER_LIMIT,
				'title_for_layout' => $this->moduleAdmin['legel_docs']['index'],
		));
	}

	/**
	 * Add news
	 *
	 */
	public function add(){
		//get category parent
		$listCategory = $this->Category->getListCategoryType(self::CAT_TYPE);
		$categories = array();
		foreach ($listCategory as $key => $category){
			$categorys = $category['categories_multi'];
			$categories[$categorys['cat_parent_id']][$categorys['id']] = $categorys;
		}

		$this->_sortLevel($categories);

		if ($this->request->is('post')) {
			$this->LegelDocs->create();

			$params = $this->request->data;
			$params['LegelDocs']['create_time'] = time();
			$params['LegelDocs']['last_update'] = time();

			$new_rewrite = CommonComponent::rewriteTitle($params['LegelDocs']['name']);
			$params['LegelDocs']['new_rewrite'] = $new_rewrite;
			$params['LegelDocs']['new_md5'] = md5(md5($new_rewrite) . Configure::read('Security.salt'));

			if (!empty($params['LegelDocs']['file'][0]['tmp_name'])){
				$upload = $this->Upload;
				$upload->uploadImage(reset($params['LegelDocs']['file']), FOLDER_UPLOAD_IMAGE);
				if ($upload->error() == ''){
					$params['LegelDocs']['new_picture'] = $upload->getFileName();
					unset($params['LegelDocs']['file']);
				} else {
					$this->Session->setFlash($upload->error(), 'error');
					$this->redirect(array('action' => 'add'));
				}
			}

			if ($this->LegelDocs->save($params)) {
				$this->Session->setFlash(__('Success'), 'success');
				$this->redirect(array('controller' => 'LegelDocs', 'action' => 'index'));
			} else {
				$this->Session->setFlash(__('Save could not be saved. Please, try again'), 'error');
			}
		}

		$this->set('listCategory', $this->categorymulti);
		$this->set('title_for_layout', $this->moduleAdmin['legel_docs']['add']);

	}

	/**
	 * Edit news
	 *
	 * @param string $id
	 */
	public function edit($id = null){
		if (!$id) {
			throw new NotFoundException(__('Invalid post'));
		}

		//get detail
		$detail = $this->LegelDocs->findById($id);
		if (!$detail) {
			throw new NotFoundException(__('Invalid post'));
		}

		//get category parent
		$listCategory = $this->Category->getListCategoryType(self::CAT_TYPE);
		$categories = array();
		foreach ($listCategory as $key => $category){
			$categorys = $category['categories_multi'];
			$categories[$categorys['cat_parent_id']][$categorys['id']] = $categorys;
		}

		$this->_sortLevel($categories);
		//edit news
		if ($this->request->is('post')) {
			$params = $this->request->data;
			$new_rewrite = CommonComponent::rewriteTitle($params['LegelDocs']['name']);
			$params['LegelDocs']['new_rewrite'] = $new_rewrite;
			$params['LegelDocs']['new_md5'] = md5(md5($new_rewrite) . Configure::read('Security.salt'));
			$params['LegelDocs']['last_update'] = time();
			//update picture
			if (!empty($params['LegelDocs']['file'][0]['tmp_name'])){
				$upload = $this->Upload;
				$upload->uploadImage(reset($params['LegelDocs']['file']), FOLDER_UPLOAD_IMAGE);
				if ($upload->error() == ''){
					$params['LegelDocs']['new_picture'] = $upload->getFileName();
					unset($params['LegelDocs']['file']);
				} else {
					$this->Session->setFlash($upload->error(), 'error');
					$this->redirect(array('action' => 'add'));
				}
			}

			$this->LegelDocs->id = $id;
			if ($this->LegelDocs->save($params)) {
				return $this->redirect(array('action' => 'index'));
			} else {

			}

		}

		//set view
		$this->set('detail', $detail);
		$this->set('listCategory', $this->categorymulti);
		$this->set('title_for_layout', $this->moduleAdmin['legel_docs']['edit']);
	}

	/**
	 * Delete news
	 *
	 * @param string $id
	 */
	public function delete($id = null){
		$this->layout = null;
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}

		$this->LegelDocs->read('id', $id);
		$this->LegelDocs->set('del_flg', 1);
		$this->LegelDocs->save();
		$this->Session->setFlash(__('Delete success'), 'success');
		return $this->redirect(array('action' => 'index'));

	}

	/**
	 * Update news
	 * @param string $id
	 * @param string $type
	 */
	public function update($id = null, $field = 'active'){
		$this->layout = null;
		$this->render(false);
		if ($this->request->is('post')) {
			$value = $this->request->data['value'];
			$this->LegelDocs->set('id', $id);
			$this->LegelDocs->set($field, $value);
			$this->LegelDocs->save();
			echo $value;
		}
	}

	/**
	 * Sap xep danh muc theo level
	 *
	 * @param array $arrayCategory
	 * @param number $keystart nút cha
	 * @param number $level
	 */
	private function _sortLevel($arrayCategory, $keystart = 0, $level = -1){
		//kiểm tra xem tồn tại record không
		if (array_key_exists($keystart, $arrayCategory)) {
			$level++;
			foreach ($arrayCategory[$keystart] as $key => $value){

				//gán các phần tử cho array menu sắp xếp theo đúng vị trí
				//tang so thu tu
				$this->stt++;
				$this->categorymulti[$this->stt] = $value;

				//gan level cho menu
				$this->categorymulti[$this->stt]['level'] = $level;

				//thiet lap de biet day la` 1 nut cha
				if (array_key_exists($key,$arrayCategory)){
					$this->categorymulti[$this->stt]["parent"] = 1;
				} else {
					$this->categorymulti[$this->stt]["parent"] = 0;
				}

				//de quy de lap lai, neu menu_id nam trong array cac menu cha
				$this->_sortLevel($arrayCategory, $key, $level);
			}
		}
	}
}
